package sketchpad.gui.component;

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import sketchpad.business.function.OperateService;
import sketchpad.business.function.impl.OperateServiceImpl;
import sketchpad.constant.Config;
import sketchpad.gui.control.DrawControl;
import sketchpad.gui.drawinggraph.DrawItem;
import sketchpad.gui.drawinggraph.node.Node;

public class MyCanvas {

    private DrawItem drawItem;
    private DrawControl drawControl;
    private final Canvas canvas;

    public MyCanvas(Stage primaryStage){
         canvas = new Canvas(Config.WINDOW_LENGTH, Config.WINDOW_WIDTH-120);
        final GraphicsContext gc = canvas.getGraphicsContext2D();
        drawControl = new DrawControl(gc,primaryStage);
    }

    public void addCanvasListener(FuncNodeList funcNodeList, PopupMenu popupMenu){
        OperateService operateService = new OperateServiceImpl(drawControl);

        canvas.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
            drawItem = drawControl.create(new Node(event.getX(),event.getY()));
        });

        canvas.addEventHandler(MouseEvent.MOUSE_DRAGGED, event -> {
            funcNodeList.reConstructNodesList();
            Node mouseNode = new Node(event.getX(), event.getY());
            if (drawControl.isReadyToMove()){
                operateService.move(mouseNode);
                drawControl.drawAllItem();
            } else drawControl.draw(drawItem.getId(),mouseNode,false);
        });

        canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            funcNodeList.reConstructNodesList();
            if (event.getButton()== MouseButton.SECONDARY){
                popupMenu.show(event.getX(),event.getY());
            }
            if (!drawControl.isSelect())drawControl.setReadyToMove(false);
        });

        canvas.addEventHandler(MouseEvent.MOUSE_RELEASED,event -> {
            if (event.getButton()==MouseButton.SECONDARY)return;
            if (drawControl.getIsSelect()){
                drawControl.setLastSelectBox(drawControl.getDrawItemMap().get(Config.SELECT_ID));
                drawControl.getDrawItemMap().remove(Config.SELECT_ID);
                drawControl.multiSelect();
                drawControl.drawAllItem();
            }
        });
    }

    public DrawControl getDrawControl() {
        return drawControl;
    }

    public Canvas getCanvas() {
        return canvas;
    }
}
